<?php 
$web = ($GET_viewProperty == 'web') ? 'web' : false;

$agendaArrayStrJs = Msa_AgendaObject::getAgendaArrayJS();
$currentAgendas = json_decode($agendaArrayStrJs);
$authorizedAgendas = Msa_AgendaObject::getEnabledAgendaArray();
$agendaIdLocationId = Msa_AgendaObject::getAgendaLocations($authorizedAgendas);
$authorizedPrestations = array();
foreach ($authorizedAgendas as $authorizedAgenda) {
    $authorizedPrestations[$authorizedAgenda] = Msa_PrestationObject::getPrestationListIdFromAgendaId($authorizedAgenda);
}
$prestationTrees = array();
foreach($authorizedAgendas as $agenda_id) {
    $agendaTree = Msa_PrestationObject::getPrestationTreeFromAgendaId($agenda_id);
    $prestationTrees[$agenda_id] = Erra_Fields_Tree::create('localitem_prestation')
            ->fill($agendaTree)
            ->setHtmlName('localitem[prestation]')
            ->editInstance();  
}
$agendaColors = Msa_AgendaObject::getAgendaColors();
?> 

<?php  if (!empty($currentAgendas)): ?>
    <?php 
    $agendaIdArrayStrJs = Msa_AgendaObject::getAgendaIdArrayJS();
    $res = '';
    $res .= '<style type="text/css">';
    $cols = Config_ConfigObject::get('jours_a_afficher') * count($currentAgendas);
    if ($cols > 19) {
        $res .= '.wc-user-header, .wc-title  { font-size:11px !important; }';
    }
    if ($cols > 29) {
        $res .= '.wc-user-header, .wc-title { font-size:10px !important; }';
    }
    $res .= '</style>';
    echo $res;
    ?>
    <script type='text/javascript'>
        // Init local storage
        var authorizedPrestas = <?php  echo  json_encode($authorizedPrestations) ?>;
        initCalendarCache(authorizedPrestas);
        initLocalStorage();

        $(document).ready(function() {
            window.accessId = "<?php  echo  Access_ControlObject::get_user_id() ?>";
            window.agendaArray = json_decode('<?php  echo  addslashes($agendaArrayStrJs) ?>');
            window.agendaIdArray = json_decode('<?php  echo  addslashes($agendaIdArrayStrJs) ?>');
            window.agendaIdLocationName = json_decode('<?php  echo  addslashes($agendaIdLocationId) ?>');
            window.authorizedAgendas = json_decode('<?php  echo  addslashes(json_encode($authorizedAgendas)) ?>');
            window.prestationTrees = json_decode('<?php  echo  addslashes(json_encode($prestationTrees)) ?>');
            window.agendasColors = json_decode('<?php  echo  addslashes(json_encode($agendaColors)) ?>');
            
            window.calendarCache['sync_interval'] = <?php  echo  Config_GeneralConfigObject::get('calendar_refresh') * 1000 ?>;
            window.calendarCache['timer'] = window.setInterval(function() {
                executeLocalStack();
            }, window.calendarCache['sync_interval']);

            var $calendar = $('#calendar');
            var calendarJsonRequest = '';
            var changeEventJsonRequest = '';


            $calendar.weekCalendar({
                date: new Date(<?php  echo  Config_ConfigObject::get('jour_de_demarrage') ?>),
                timeslotsPerHour: <?php  echo  Config_ConfigObject::get('nb_intervalles_par_heure') ?>,
                allowCalEventOverlap: true,
                overlapEventsSeparate: true,
                startOnFirstDayOfWeek: false,
                businessHours: {start: <?php  echo  Config_ConfigObject::get('heure_de_debut') ?>, end: <?php  echo  Config_ConfigObject::get('heure_de_fin') ?>, limitDisplay: true},
                daysToShow: <?php  echo  Config_ConfigObject::get('jours_a_afficher') ?>,
                timeFormat: 'H:i',
                dateFormat: 'M d, Y',
                use24Hour: true,
                displayFreeBusys: true,
                showHeader: false,
                hourLine: true,
                // I18N
                firstDayOfWeek: $.datepicker.regional['fr'].firstDay,
                shortDays: $.datepicker.regional['fr'].dayNamesShort,
                longDays: $.datepicker.regional['fr'].dayNames,
                shortMonths: $.datepicker.regional['fr'].monthNamesShort,
                longMonths: $.datepicker.regional['fr'].monthNamesShort,
                dateFormat: 'd F Y',
                        height: function($calendar) {
                    return $(window).height() - $("#header").outerHeight() - 15;
                },
                calendarAfterLoad: function(calendar) {
                    erraRenderNotes(calendar);
                    erraRenderLocations();
                },
                eventRender: function(calEvent, $event) {
                    erraRenderEvent(calEvent, $event);
                },
                draggable: function(calEvent, $event) {
                    return calEvent.readOnly != true;
                },
                resizable: function(calEvent, $event) {
                    return (calEvent.event_type == 'presta') ? false : true;
                },
                beforeEventNew: function($event, ui) {
                    ui.calEvent.title = "Nouvel évènement";
                    ui.calEvent.createdFromSingleClick = ui.createdFromSingleClick;
                },
                newEventText: 'Evènement',
                eventNew: function(calEvent, $event) {
                    slot_object_init_static(calEvent);
                },
                eventDrop: function(newCalEvent, oldCalEvent) {
                    var newAgendaId = parseInt(window.agendaIdArray[newCalEvent.userId]);
                    var slot_day = parseInt(timestamp_to_day_time_php(new Date(newCalEvent.start).getTime()));
                    var slot_start = parseInt((new Date(newCalEvent.start).getTime() / 1000) - slot_day);
                    var slot_end = parseInt((new Date(newCalEvent.end).getTime() / 1000) - slot_day);
                    // Check if event changed user
                    if (newCalEvent.event_type == "presta" && newCalEvent.userId != oldCalEvent.userId) {
                        canReattributeEvent(newCalEvent, newAgendaId, function() {
                            newCalEvent.agenda_id = newAgendaId;
                            newCalEvent.slot_day = slot_day;
                            newCalEvent.slot_start = slot_start;
                            newCalEvent.slot_end = slot_end;
                            addToLocalStore('MOVE_EVENT', newCalEvent);
                        }, function() {
                            notification_jqueryui("L'agenda de destination ne prend pas en charge cette prestation");
                            newCalEvent.start = oldCalEvent.start;
                            newCalEvent.end = oldCalEvent.end;
                            newCalEvent.userId = oldCalEvent.userId;
                        });
                    } else {
                        newCalEvent.agenda_id = newAgendaId;
                        newCalEvent.slot_day = slot_day;
                        newCalEvent.slot_start = slot_start;
                        newCalEvent.slot_end = slot_end;
                        if (newCalEvent.event_type == "presta") {
                            //     sendConfirmation(newCalEvent);
                        }
                        addToLocalStore('MOVE_EVENT', newCalEvent);
                    }
                },
                eventResize: function(newCalEvent, oldCalEvent, $event) {
                    var newAgendaId = parseInt(window.agendaIdArray[newCalEvent.userId]);
                    var slot_day = parseInt(timestamp_to_day_time_php(new Date(newCalEvent.start).getTime()));
                    var slot_start = parseInt((new Date(newCalEvent.start).getTime() / 1000) - slot_day);
                    var slot_end = parseInt((new Date(newCalEvent.end).getTime() / 1000) - slot_day);
                    newCalEvent.agenda_id = newAgendaId;
                    newCalEvent.slot_day = slot_day;
                    newCalEvent.slot_start = slot_start;
                    newCalEvent.slot_end = slot_end;
                    addToLocalStore('RESIZE_SLOT', newCalEvent);
                },
                eventClick: function(calEvent, $event) {
                    if (calEvent.readOnly) {
                        return;
                    }
                    // Check if close button has been clicked 
                    if ($('#delete-event-' + calEvent.id + '-' + calEvent.occurency).data('clicked') == true) {
                        $('#delete-event-' + calEvent.id + '-' + calEvent.occurency).data('clicked', false);
                        delete_event(calEvent);
                    } else {
                        // Do the magic here
                        slot_object_init_static(calEvent);
                    }
                    
                },
                eventMouseover: function(calEvent, $event) {
                },
                eventMouseout: function(calEvent, $event) {
                },
                noEvents: function() {

                },
                users: window.agendaArray,
                data: function(start, end, callback) {
                    startTime = new Date(start).getTime();
                    endTime = new Date(end).getTime();
                    get_cache_infos(startTime, endTime, "<?php  echo  $web ?>", function(data) {
                        callback(data);
                        erraPostRender();
                    });
                }
            });

        });
    </script>

    <div id='calendar'></div>
    <div style="display:none;">
        <div id="delete-slot-window" title="Supprimer cet évènement">                            
            <p>Etes vous sur de vouloir supprimer cet évènement ?</p>
        </div>

        <div id="handle-note" title="Editer une note">                            
            <p>Vous pouvez éditer ci dessous une note correspondant aux informations de la journée</p>
            <textarea cols="40" rows="3"></textarea>
        </div>
    </div>
    <input type="hidden" id="slot-edit-data">

<?php  else : ?>
    <br/>
    Aucun agenda affichable pour cet utilisateur, veuillez sélectioner le(s) agenda(s) à afficher sur "Option d'affichage", puis <a href="<?php  echo  Erra_System_PageBuilder::makeLink('calendar') ?>">Cliquez ici</a> pour recharger la page 
<?php  endif; ?>

<?php 
print '<div style="display:none;">';
print Msa_SlotObject::getObject(uniqid(), 'CREATE', null, $web)
                ->addAttribute('class', 'manual_editable_in_place slot-edit')
                ->_editInPlace('SaveAction/saveSlot', 'HIDDEN_SLOT_OBJECT');
print '</div>';

$field = Msa_SlotObject::getObject('localitem', 'CREATE', null, $web)
        ->addAttribute('class', 'manual_editable_in_place')
        ->setAjax(false);

print '<did id="FORMCONTAINER_localitem" style="display:none; left: 50%; position: absolute; top: 0; z-index: 1001; margin-left:-225px;">';
print '<div id="EXIT_dialog" title="Quitter"></div>';
print '<div id="EDIT_IN_PLACE_' . $field->getObjectId() . '" ' . $field->getHtmlAttributes() . ' data-object="' . $field->getTableName() . '">' . Erra_System_FormRenderer::editField($field, 'saveActionLocalStorage', true) . '</div>';
print '</div>';
?>